package com.dsl.dslsuzhou.service;


import com.dsl.dslsuzhou.engine.BuiltSql;
import com.dsl.dslsuzhou.engine.DslSqlBuilder;
import com.dsl.dslsuzhou.mapper.JdbcExecutor;
import com.dsl.dslsuzhou.model.NameCategoryDimension;
import com.dsl.dslsuzhou.model.NameCategoryDimensionMore;
import com.dsl.dslsuzhou.model.NameCategoryDimensionTwo;
import com.dsl.dslsuzhou.model.entity.dsl.ChartDsl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 图表服务
 */
@Service
public class ChartService {
    
    @Autowired
    private JdbcExecutor jdbcExecutor;
    
    /**
     * 执行图表查询
     */
    public Object executeChart(ChartDsl dsl) {
        // 构建SQL
        BuiltSql builtSql = DslSqlBuilder.buildQuery(dsl);

        // 执行查询
        List<Map<String, Object>> results = jdbcExecutor.executeQuery(builtSql);

        // 检查是否是对比分析
        boolean isCompare = dsl.getCompare() != null &&
                           (Boolean.TRUE.equals(dsl.getCompare().getYoy()) ||
                            Boolean.TRUE.equals(dsl.getCompare().getMom()));

        // 检查是否是占比分析
        boolean isProportion = dsl.getCompare() != null &&
                              Boolean.TRUE.equals(dsl.getCompare().getProportion());

        if (isProportion) {
            // 占比分析：返回NameCategoryDimensionTwo格式（两列数据）
            return convertToNameCategoryDimensionTwo(results, dsl);
        } else if (isCompare) {
            // 对比分析：返回NameCategoryDimensionMore格式
            return convertToNameCategoryDimensionMore(results, dsl);
        } else {
            // 普通查询：返回NameCategoryDimension格式
            return convertToNameCategoryDimension(results, dsl);
        }
    }
    
    /**
     * 转换查询结果为NameCategoryDimension格式
     */
    private List<NameCategoryDimension<BigDecimal>> convertToNameCategoryDimension(
            List<Map<String, Object>> results, ChartDsl dsl) {

        List<NameCategoryDimension<BigDecimal>> list = new ArrayList<>();

        // 检查是否是占比分析
        boolean isProportion = dsl.getCompare() != null && Boolean.TRUE.equals(dsl.getCompare().getProportion());

        for (Map<String, Object> row : results) {
            String bucket = String.valueOf(row.get("bucket"));

            BigDecimal value;

            if (isProportion) {
                // 占比分析：返回占比率作为category1
                value = convertToBigDecimal(row.get("proportion_rate"));
            } else {
                // 普通查询：获取值字段
                String valueField = getValueField(dsl);
                Object valueObj = row.get(valueField);
                value = convertToBigDecimal(valueObj);
            }

            // 格式化为2位小数
            if (value != null) {
                value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
            }

            list.add(new NameCategoryDimension<>(bucket, value));
        }

        return list;
    }

    /**
     * 转换查询结果为NameCategoryDimensionMore格式（用于对比分析）
     */
    private List<NameCategoryDimensionMore<BigDecimal>> convertToNameCategoryDimensionMore(
            List<Map<String, Object>> results, ChartDsl dsl) {

        List<NameCategoryDimensionMore<BigDecimal>> list = new ArrayList<>();

        boolean isYoy = dsl.getCompare() != null && Boolean.TRUE.equals(dsl.getCompare().getYoy());
        boolean isMom = dsl.getCompare() != null && Boolean.TRUE.equals(dsl.getCompare().getMom());
        boolean isProportion = dsl.getCompare() != null && Boolean.TRUE.equals(dsl.getCompare().getProportion());

        for (Map<String, Object> row : results) {
            String bucket = String.valueOf(row.get("bucket"));

            BigDecimal category1, category2, category3;

            if (isProportion) {
                // 占比：当日耗水量、占比率、不使用第三列
                category1 = convertToBigDecimal(row.get("detail_value"));
                category2 = convertToBigDecimal(row.get("proportion_rate"));
                category3 = null; // 不使用第三列
            } else if (isYoy) {
                // 同比：去年值、今年值、同比增长率
                category1 = convertToBigDecimal(row.get("last_year_value"));
                category2 = convertToBigDecimal(row.get("current_year_value"));
                category3 = convertToBigDecimal(row.get("yoy_growth_rate"));
            } else if (isMom) {
                // 环比：上期值、当期值、环比增长率
                category1 = convertToBigDecimal(row.get("last_period_value"));
                category2 = convertToBigDecimal(row.get("current_period_value"));
                category3 = convertToBigDecimal(row.get("mom_growth_rate"));
            } else {
                // 默认处理
                category1 = convertToBigDecimal(row.get("current_value"));
                category2 = convertToBigDecimal(row.get("compare_value"));
                category3 = BigDecimal.ZERO;
            }

            // 格式化为2位小数
            if (category1 != null) {
                category1 = category1.setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            if (category2 != null) {
                category2 = category2.setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            if (category3 != null) {
                category3 = category3.setScale(2, BigDecimal.ROUND_HALF_UP);
            }

            list.add(new NameCategoryDimensionMore<>(bucket, category1, category2, category3));
        }

        return list;
    }

    /**
     * 转换查询结果为NameCategoryDimensionTwo格式（用于占比分析）
     */
    private List<NameCategoryDimensionTwo<BigDecimal>> convertToNameCategoryDimensionTwo(
            List<Map<String, Object>> results, ChartDsl dsl) {

        List<NameCategoryDimensionTwo<BigDecimal>> list = new ArrayList<>();

        for (Map<String, Object> row : results) {
            String bucket = String.valueOf(row.get("bucket"));

            // 占比分析：当日耗水量、占比率（都保留2位小数）
            BigDecimal category1 = convertToBigDecimal(row.get("detail_value"));
            BigDecimal category2 = convertToBigDecimal(row.get("proportion_rate"));

            // 格式化为2位小数
            if (category1 != null) {
                category1 = category1.setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            if (category2 != null) {
                category2 = category2.setScale(2, BigDecimal.ROUND_HALF_UP);
            }

            list.add(new NameCategoryDimensionTwo<>(bucket, category1, category2));
        }

        return list;
    }

    /**
     * 获取值字段名
     */
    private String getValueField(ChartDsl dsl) {
        if (!CollectionUtils.isEmpty(dsl.getMetrics())) {
            // 使用第一个指标
            return dsl.getMetrics().get(0).getName();
        } else {
            // 默认值字段
            return "value";
        }
    }
    
    /**
     * 转换为BigDecimal
     */
    private BigDecimal convertToBigDecimal(Object value) {
        if (value == null) {
            return BigDecimal.ZERO;
        }
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof Number) {
            return new BigDecimal(value.toString());
        }
        try {
            return new BigDecimal(value.toString());
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
    }
}
